package cn.lz;

import cn.lz.pojo.tang;
import cn.lz.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.istack.internal.logging.Logger;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;

import java.util.Date;

import static cn.lz.util.JSONUtils.isJSONValid;

/**
 * @author: TT
 * @date: 2018/12/24
 * @time: 12:30
 * @version: 心跳工厂 V1.0
 */
public class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory {

    private final Logger LOG = Logger.getLogger(KeepAliveMessageFactoryImpl.class);

    /** 心跳包内容 */
    private static final String HEARTBEATREQUEST = "1111";
    private static final String HEARTBEATRESPONSE = "1112";

    public Object getRequest(IoSession session) {

//        tang t =new tang();
//
//        // I-心跳
//        //  协议：000069{"RE":"Y","OD":"5896348_1","CD":"I","ID":"5896348","TM":"1526377009"}
//        t.setRE("Y");
//        t.setOD("5896348_1");
//        t.setCD("I");
//        t.setID("5896348");
//        t.setTM(DateUtils.UnixDate(new Date()));
//
//        //对象转json
//        String s = JSONObject.toJSONString(t);
//        //拼接的数据
//        String reply=String.format("%06d", s.length())+s;
//
//        LOG.info("请求预设信息: " + reply);
        return false;
    }
    public Object getResponse(IoSession session, Object request) {
        LOG.info("服务端接收心跳请求数据 " + request);
        /** 返回预设语句 */

        String string= (String) request;
        tang t =new tang();
        String reply="";

        JSONObject jsonObject =null;
        //转对象
        if(isJSONValid(string)){
            //是标准的json串
            jsonObject = JSON.parseObject(string);
        }else {
            //不是标准的json串
            jsonObject = JSON.parseObject( string.substring(6));
        }

        // I-心跳
        if(jsonObject.get("CD")!=null&&jsonObject.get("CD").equals("I")){
            //  协议：000069{"RE":"Y","OD":"5896348_1","CD":"I","ID":"5896348","TM":"1526377009"}
            t.setRE("Y");
            t.setOD("5896348_1");
            t.setCD("I");
            t.setID("5896348");
            t.setTM(DateUtils.UnixDate(new Date()));

            //对象转json
            String s = JSONObject.toJSONString(t);
            //拼接的数据
            reply=String.format("%06d", s.length())+s;

            session.write(reply);
        }

        return t;
    }
    public boolean isRequest(IoSession session, Object message) {
        LOG.info("服务端判断消息是否为请求包消息: " + message);

        return false;
    }
    public boolean isResponse(IoSession session, Object message) {
        LOG.info("服务端判断响应心跳包信息: " + message);

        return false;
    }


}
